#coding=utf-8

'''
Created on 2011-8-30

@author: chris
'''
from ripper.parser.Parser import Parser
import os.path
import datetime

class TTCNParser(Parser):

    '''
        tabletenisdb站网页文本解析器
    '''
        
    # 解析球拍列表
    def parse_obj_list(self, pageIndex, keyProp, otherProps, item):
        soup = self.get_soup(url=pageIndex.url)
        # 对象列表
        blades = []
        # 品牌下拉div
        brandDivs = soup.findAll('div', {'class' : 'dbcat'})
        for brandDiv in brandDivs:
            
            # 品牌名称
            brandName = brandDiv.contents[0].text
            brandName = brandName[: brandName.rindex('(')].strip() # 去掉 (No Brand) (2) 后面的数目
            
            # 目标列表div的id
            b1 = brandDiv['onclick']
            b3 = b1.split("'")[1]
            dropDownBrandListDivId = b3
            ddblDiv = soup.findAll('div', {'id' : dropDownBrandListDivId})[0]
            bladeListA = ddblDiv.findAll('a', {'class' : 'dbitem'})
            
            # 球拍详细链接<a>
            for bladeA in bladeListA:
                
                # 不同python版本的问题
                _bladeName, _bladeUrl = None, None
                if type(bladeA.attrs) == 'dict':
                    _bladeName, _bladeUrl = bladeA.attrs['title'],  bladeA.attrs['href']
                else:
                    _bladeName, _bladeUrl = bladeA.attrs[-2][1],  bladeA.attrs[-1][1]
                
                _bladeUrl = os.path.join('http://www.tabletennisdb.com/blade/', _bladeUrl)
                blades.append({'bladeBrandName' : brandName, 
                               'bladeName' : _bladeName, 
                               'bladeDetailUrl' : _bladeUrl})
        
               
        return blades
    
    def __getRatings(self, url, idx, className='rating'):
        soup = self.get_soup(url=url)
        # 对象列表
        ratings = soup.findAll('td', {'class' : className})
        td = ratings[idx]
        txt = td.text
        if txt != None:
            txt = txt.rstrip().lstrip()
        return txt
    
    # 解析属性
    def get_collectDate(self, url, prop, obj):
        return datetime.datetime.utcnow()
    
    # 解析属性
    def get_speedFromManufacturer(self, url, prop, obj):
        return self.__getRatings(url, 0)
    
    # 解析属性
    def get_controlFromManufacturer(self, url, prop, obj):
        return self.__getRatings(url, 1)
    
    # 解析属性
    def get_weightFromManufacturer(self, url, prop, obj):
        return self.__getRatings(url, 2)
    
    # 解析属性
    def get_speedFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 0, 'rating firstrating')
    
    # 解析属性
    def get_controlFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 3)
    
    # 解析属性
    def get_stiffnessFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 4)
    
    # 解析属性
    def get_hardnessFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 5)
    
    # 解析属性
    def get_consistencyFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 6)
    
    # 解析属性
    def get_overallFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 0, 'rating overallbg2')
    
    # 解析属性
    def get_pliesFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 7)
    
    # 解析属性
    def get_materialsFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 8)
    
    # 解析属性
    def get_headThicknessFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 9)
    
    # 解析属性
    def get_headDimensionsFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 10)
    
    # 解析属性
    def get_handleDimensionsFromCommunity(self, url, prop, obj):
        return self.__getRatings(url, 11)
    
    # 解析属性
    def get_bladePrice(self, url, prop, obj):
        soup = self.get_soup(url=url)
        priceSpan = soup.findAll('span', {'id' : 'actual_price'})
        price = priceSpan[0].text
        return price
    
    # 解析属性
    def get_bladePicture(self, url, prop, obj):
        soup = self.get_soup(url=url)
        img = soup.findAll('meta', {'property' : 'og:image'})
        if len(img) == 0:
            return ''
        imgUrl = img[0]['content']
        return imgUrl
    
    # 解析属性
    def get_bladeReviews(self, url, prop, obj):
        return 'REVIEWS'
    
    def parse_index(self):
        text = open('h:/Table Tennis Blades.htm').read()
        soup = self.get_soup(text=text)
#        soup = self.get_soup(url='http://www.tabletennisdb.com/blade/')
        # 对象列表
        blades = []
        # 品牌下拉div
        brandDivs = soup.findAll('div', {'class' : 'dbcat'})
        for brandDiv in brandDivs:
            
            # 品牌名称
            brandName = brandDiv.contents[0].text
            brandName = brandName[: brandName.rindex('(')].strip() # 去掉 (No Brand) (2) 后面的数目
            
            # 目标列表div的id
            b1 = brandDiv['onclick']
            b3 = b1.split("'")[1]
            dropDownBrandListDivId = b3
            ddblDiv = soup.findAll('div', {'id' : dropDownBrandListDivId})[0]
            bladeListA = ddblDiv.findAll('a', {'class' : 'dbitem'})
            
            # 球拍详细链接<a>
            for bladeA in bladeListA:
                
                # 不同python版本的问题
                _bladeName, _bladeUrl = None, None
                if type(bladeA.attrs) == 'dict':
                    _bladeName, _bladeUrl = bladeA.attrs['title'],  bladeA.attrs['href']
                else:
                    _bladeName, _bladeUrl = bladeA.attrs[-2][1],  bladeA.attrs[-1][1]
                    
                blades.append({'bladeBrandName' : brandName, 
                               'bladeName' : _bladeName, 
                               'bladeDetailUrl' : _bladeUrl})
        print len(blades)         
        return blades
    
    def parse_detail(self):
        text = open('h:/Best of Five Dynatec Ti Reviews.htm').read()
        soup = self.get_soup(text=text)
        ratings = soup.findAll('td', {'class' : 'rating'})
        fratings = soup.findAll('td', {'class' : 'rating firstrating'})
        td = ratings[0]
             
        img = soup.findAll('meta', {'property' : 'og:image'})
        print img[0]['content']
        
        priceSpan = soup.findAll('span', {'id' : 'actual_price'})
        price = priceSpan[0].text
        print price
        
if __name__ == '__main__':
    parser = TTCNParser(None)
    parser.parse_index()
        